#!/usr/bin/env node

/**
 * Configuration Validation Script
 * 验证Vision Analyzer的配置是否正确
 */

const fs = require('fs');
const path = require('path');

class ConfigValidator {
    constructor() {
        this.projectRoot = path.resolve(__dirname, '..');
    }

    /**
     * 显示标题
     */
    showHeader() {
        console.log('\n🔍 Vision Analyzer 配置验证');
        console.log('===============================');
    }

    /**
     * 验证配置文件是否存在
     */
    validateConfigFileExists() {
        console.log('\n📁 检查配置文件...');

        try {
            const ConfigPathResolver = require('../lib/config/config-path-resolver');
            const pathResolver = new ConfigPathResolver();
            const configPath = pathResolver.getConfigFilePath();

            console.log(`📍 配置文件路径: ${configPath}`);

            if (!fs.existsSync(configPath)) {
                console.log('❌ 配置文件不存在');
                return {
                    exists: false,
                    path: configPath,
                    error: '配置文件不存在'
                };
            }

            console.log('✅ 配置文件存在');
            return {
                exists: true,
                path: configPath
            };
        } catch (error) {
            console.log('❌ 无法确定配置文件路径:', error.message);
            return {
                exists: false,
                path: null,
                error: error.message
            };
        }
    }

    /**
     * 验证配置文件格式
     */
    validateConfigFormat(configPath) {
        console.log('\n📋 检查配置文件格式...');

        if (!configPath || !fs.existsSync(configPath)) {
            console.log('❌ 配置文件不存在，无法验证格式');
            return false;
        }

        try {
            const configContent = fs.readFileSync(configPath, 'utf8');
            const config = JSON.parse(configContent);

            console.log('✅ JSON格式有效');

            // 检查必需的配置项
            const requiredFields = ['providers', 'current_provider'];
            const missingFields = requiredFields.filter(field => !(field in config));

            if (missingFields.length > 0) {
                console.log('⚠️  缺少必需的配置项:', missingFields.join(', '));
                return false;
            }

            console.log('✅ 包含所有必需的配置项');

            // 检查providers配置
            if (!config.providers || typeof config.providers !== 'object') {
                console.log('❌ providers配置无效');
                return false;
            }

            const providers = Object.keys(config.providers);
            if (providers.length === 0) {
                console.log('⚠️  没有配置任何服务商');
                return false;
            }

            console.log(`✅ 已配置 ${providers.length} 个服务商: ${providers.join(', ')}`);

            // 检查当前提供商
            if (!config.current_provider || !providers.includes(config.current_provider)) {
                console.log('⚠️  当前提供商配置无效');
                return false;
            }

            console.log(`✅ 当前提供商: ${config.current_provider}`);

            return true;
        } catch (error) {
            console.log('❌ 配置文件格式错误:', error.message);
            return false;
        }
    }

    /**
     * 验证API密钥格式
     */
    async validateApiKeys() {
        console.log('\n🔑 检查API密钥格式...');

        try {
            const ConfigManager = require('../config-manager');
            const configManager = new ConfigManager(this.projectRoot);

            const status = await configManager.getConfigurationStatus(false);

            if (!status.hasConfigFile) {
                console.log('❌ 配置文件不存在');
                return false;
            }

            if (status.placeholderIssues.length > 0) {
                console.log('❌ 发现占位符API密钥:');
                status.placeholderIssues.forEach(issue => {
                    console.log(`   • ${issue}`);
                });
                return false;
            }

            if (status.configuredProviders.length === 0) {
                console.log('❌ 没有配置有效的API密钥');
                return false;
            }

            console.log('✅ API密钥格式检查通过');
            console.log(`🔧 已配置的服务商: ${status.configuredProviders.join(', ')}`);

            return true;
        } catch (error) {
            console.log('❌ 验证API密钥失败:', error.message);
            return false;
        }
    }

    /**
     * 验证API连接
     */
    async validateApiConnection() {
        console.log('\n🌐 测试API连接...');

        try {
            const ConfigManager = require('../config-manager');
            const configManager = new ConfigManager(this.projectRoot);

            const status = await configManager.getConfigurationStatus(true);

            if (!status.apiValidation.enabled) {
                console.log('⚠️  API验证未启用');
                return false;
            }

            if (status.apiValidation.validatedProviders.length > 0) {
                console.log('✅ API连接测试成功:');
                status.apiValidation.validatedProviders.forEach(provider => {
                    console.log(`   • ${provider.name}: ${provider.modelCount}个模型可用`);
                    if (provider.models && provider.models.length > 0) {
                        console.log(`     模型: ${provider.models.slice(0, 3).join(', ')}${provider.models.length > 3 ? '...' : ''}`);
                    }
                });
                return true;
            }

            if (status.apiValidation.invalidProviders.length > 0) {
                console.log('❌ API连接测试失败:');
                status.apiValidation.invalidProviders.forEach(provider => {
                    console.log(`   • ${provider.name}: ${provider.error}`);
                });
                return false;
            }

            if (status.apiValidation.validationErrors.length > 0) {
                console.log('❌ API验证出错:');
                status.apiValidation.validationErrors.forEach(error => {
                    console.log(`   • ${error.provider}: ${error.error}`);
                });
                return false;
            }

            console.log('⚠️  没有可用的API连接');
            return false;
        } catch (error) {
            console.log('❌ API连接测试失败:', error.message);
            console.log('💡 这可能是由于网络问题或API密钥无效导致的');
            return false;
        }
    }

    /**
     * 验证项目结构
     */
    validateProjectStructure() {
        console.log('\n📂 检查项目结构...');

        const requiredDirs = [
            'lib',
            'config',
            'tests'
        ];

        const requiredFiles = [
            'index.js',
            'analyze.js',
            'package.json',
            'settings.json.example'
        ];

        let allValid = true;

        // 检查目录
        console.log('📁 检查必需目录:');
        requiredDirs.forEach(dir => {
            const dirPath = path.join(this.projectRoot, dir);
            if (fs.existsSync(dirPath) && fs.statSync(dirPath).isDirectory()) {
                console.log(`  ✅ ${dir}/`);
            } else {
                console.log(`  ❌ ${dir}/ (缺失)`);
                allValid = false;
            }
        });

        // 检查文件
        console.log('📄 检查必需文件:');
        requiredFiles.forEach(file => {
            const filePath = path.join(this.projectRoot, file);
            if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
                console.log(`  ✅ ${file}`);
            } else {
                console.log(`  ❌ ${file} (缺失)`);
                allValid = false;
            }
        });

        if (allValid) {
            console.log('✅ 项目结构完整');
        } else {
            console.log('⚠️  项目结构不完整');
        }

        return allValid;
    }

    /**
     * 检查依赖项
     */
    validateDependencies() {
        console.log('\n📦 检查依赖项...');

        try {
            const packageJsonPath = path.join(this.projectRoot, 'package.json');
            const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));

            // 检查node_modules目录
            const nodeModulesPath = path.join(this.projectRoot, 'node_modules');
            if (!fs.existsSync(nodeModulesPath)) {
                console.log('❌ node_modules目录不存在，请运行 npm install');
                return false;
            }

            console.log('✅ node_modules目录存在');

            // 检查关键依赖
            const criticalDeps = ['@modelcontextprotocol/sdk'];
            let allDepsValid = true;

            criticalDeps.forEach(dep => {
                const depPath = path.join(nodeModulesPath, dep);
                if (fs.existsSync(depPath)) {
                    console.log(`  ✅ ${dep}`);
                } else {
                    console.log(`  ❌ ${dep} (缺失)`);
                    allDepsValid = false;
                }
            });

            if (allDepsValid) {
                console.log('✅ 关键依赖项完整');
            } else {
                console.log('⚠️  缺少关键依赖项，请运行 npm install');
            }

            return allDepsValid;
        } catch (error) {
            console.log('❌ 检查依赖项失败:', error.message);
            return false;
        }
    }

    /**
     * 显示修复建议
     */
    showFixSuggestions(validationResults) {
        console.log('\n🔧 修复建议:');
        console.log('=============');

        if (!validationResults.configFile.exists) {
            console.log('\n📋 配置文件问题:');
            console.log('• 运行: node scripts/setup-wizard.js');
            console.log('• 或手动复制 settings.json.example 到配置位置');
        }

        if (!validationResults.configFormat) {
            console.log('\n📋 配置格式问题:');
            console.log('• 检查JSON语法是否正确');
            console.log('• 确保包含必需的配置项: providers, current_provider');
        }

        if (!validationResults.apiKeys) {
            console.log('\n🔑 API密钥问题:');
            console.log('• 运行: node scripts/setup-wizard.js');
            console.log('• 或编辑配置文件，替换占位符API密钥');
        }

        if (!validationResults.apiConnection) {
            console.log('\n🌐 API连接问题:');
            console.log('• 检查网络连接');
            console.log('• 验证API密钥是否正确');
            console.log('• 确认API配额是否充足');
        }

        if (!validationResults.projectStructure) {
            console.log('\n📂 项目结构问题:');
            console.log('• 重新克隆项目或恢复缺失的文件');
            console.log('• 确保从Git仓库完整检出');
        }

        if (!validationResults.dependencies) {
            console.log('\n📦 依赖项问题:');
            console.log('• 运行: npm install');
            console.log('• 清理缓存: npm cache clean --force');
        }
    }

    /**
     * 运行完整的配置验证
     */
    async run() {
        this.showHeader();

        const validationResults = {
            configFile: this.validateConfigFileExists(),
            configFormat: false,
            apiKeys: false,
            apiConnection: false,
            projectStructure: this.validateProjectStructure(),
            dependencies: this.validateDependencies()
        };

        // 只有在配置文件存在时才进行后续验证
        if (validationResults.configFile.exists) {
            validationResults.configFormat = this.validateConfigFormat(validationResults.configFile.path);

            if (validationResults.configFormat) {
                validationResults.apiKeys = await this.validateApiKeys();

                if (validationResults.apiKeys) {
                    validationResults.apiConnection = await this.validateApiConnection();
                }
            }
        }

        // 显示总结
        console.log('\n📊 验证结果总结:');
        console.log('=================');

        const allPassed = Object.values(validationResults).every(result => result === true);

        if (allPassed) {
            console.log('🎉 所有检查都通过了！配置完全正确。');
        } else {
            console.log('⚠️  发现一些问题需要解决。');
            this.showFixSuggestions(validationResults);
        }

        console.log('\n💡 需要帮助？');
        console.log('• 查看文档: README.md');
        console.log('• 运行设置向导: node scripts/setup-wizard.js');
        console.log('• 重新测试: npm test');

        return allPassed;
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    const validator = new ConfigValidator();
    validator.run()
        .then(success => {
            process.exit(success ? 0 : 1);
        })
        .catch(error => {
            console.error('❌ 配置验证失败:', error);
            process.exit(1);
        });
}

module.exports = ConfigValidator;